package com.dayaokeji.rhythmschoolstudent.client.common.resource

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.utils.FileExtUtil
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.api.ResourceApi
import com.dayaokeji.server_api.domain.FileInfo
import com.litesuits.common.io.FilenameUtils
import com.yanzhenjie.permission.Permission
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_share_resource_detail.*
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ShareResourceDetailActivity : BaseActivity() {

    companion object {
        private const val FILE_INFO = "file_info";

        fun navigation(context: Context, fileInfo: FileInfo) {
            val intent = Intent(context, ShareResourceDetailActivity::class.java)
            intent.putExtra(FILE_INFO, fileInfo)
            context.startActivity(intent)
        }
    }

    private lateinit var fileInfo: FileInfo
    private var downloadCall: Call<ResponseBody>? = null
    private val resourceApi by lazy { ApiUtils.getApi(ResourceApi::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share_resource_detail)
        toolbar?.let {
            setSupportActionBar(it)
        }

        init()
    }

    private fun init() {
        try {
            fileInfo = intent.getSerializableExtra(FILE_INFO) as FileInfo
        } catch (e: Exception) {
            ToastUtils.info("文件信息不合法")
            return
        }
        setupViewData()
    }

    private fun setupViewData() {
        openOrDownload()
        ivFileIcon.setImageResource(FileExtUtil.getFileExtIcon(FilenameUtils.getExtension(fileInfo.name)))
        val sizeToString = com.litesuits.common.utils.FileUtil.formatFileSizeToString(fileInfo.size)
        tvFileName.text = "${fileInfo.name} (${sizeToString})"
    }

    private fun openOrDownload() {
        if (FileUtil.isFileExists(fileInfo.name)) {
            btnDownloadFile.text = "打开文件"
        } else {
            btnDownloadFile.text = "下载"
        }
    }

    /**
     * 下载文件
     */
    fun downloadClick(view: View) {
        if (PermissionUtil.hasPermission(Permission.Group.STORAGE)) {
            if (FileUtil.isFileExists(fileInfo.name)) {
                FileUtil.openFile(this, fileInfo);
            } else {
                downloadFile(fileInfo)
            }
        } else {
            checkStorePermission()
        }
    }

    /**
     * 检查存储权限
     */
    private fun checkStorePermission() {
        val build = PermissionUtil.Build()
        build.permissions = Permission.Group.STORAGE
        build.tips = "请允许我们访问存储权限，方便您下载和上传文件"
        addDisposable(PermissionUtil.checkPermission(this, build).subscribe(storeConsumer))
    }

    private val storeConsumer = Consumer<PermissionUtil.PermissionResult> { permissionResult ->
        if (!permissionResult.isHasAccess) {
            checkStorePermission()
        }
    }

    /**
     * 下载文件
     * @param fileInfo
     */
    private fun downloadFile(fileInfo: FileInfo) {
        if (FileUtil.isFileExists(fileInfo.name) || TextUtils.isEmpty(fileInfo.id)) {
            return
        }
        val progressDialog = ProgressDialog(this)
        progressDialog.setTitle("正在下载" + fileInfo.name)
        progressDialog.show()
        downloadCall = resourceApi.download(fileInfo.id)
        downloadCall?.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful) {
                    FileUtil.saveFile(response.body(), fileInfo)
                    openOrDownload()
                } else {
                    ToastUtils.error(getString(R.string.file_download_failure))
                }
                progressDialog?.let {
                    it.dismiss()
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                ToastUtils.error(getString(R.string.file_download_failure))
                progressDialog?.let {
                    it.dismiss()
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        downloadCall?.cancel()
    }
}
